package com.glory.brepda.activity.mfg;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.github.chrisbanes.photoview.PhotoView;
import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.entity.DrawingpathEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;

public class ImageMainActivity extends BaseActivity {

//    @BindView(R.id.image.txt)
//    ImageView image.txt;
    @BindView(R.id.image)
    PhotoView image;

    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.imagename)
    FreeUI_ClearEditText imagename;
    @BindView(R.id.lotScan)
    ImageView lotScan;
    @BindView(R.id.imageScan)
    ImageView imageScan;
    private static final int REQUEST_CODE_TEXT1 = 1001;
    private static final int REQUEST_CODE_TEXT2 = 1002;

    public static void showImage(Context context, String uri, ImageView iv) {
//        FileInputStream fs = new FileInputStream(uri);
//        BufferedInputStream bs = new BufferedInputStream(fs);
//        Bitmap btp = BitmapFactory.decodeStream(bs);
//        iv.setImageBitmap(btp);
//        bs.close();
//        fs.close();
//        btp = null;
//        BitmapFactory.Options opts = new BitmapFactory.Options();
//        opts.inSampleSize = 2;

//        Bitmap bitmap = BitmapFactory.decodeByteArray(uri, 0, uri.length,opts);

        if (stringtoBitmap(uri) != null) {
            iv.setImageBitmap(stringtoBitmap(uri));
        } else {
            iv.setImageDrawable(MyApp.app.getResources().getDrawable(R.drawable.ic_launcher_background));
        }

    }

    public static Bitmap stringToBitmap(String string) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray = Base64.decode(string.split(",")[1], Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static Bitmap stringtoBitmap(String string) {
        //将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_image;
    }

    @Override
    protected void initView() {

        setMainLayout(llMain);

        initEdit(etLot, s -> {
            //获取lot信息
            image.setVisibility(View.GONE);
            LotUtils.searchLotInfo(ImageMainActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    drawingpathData(response.getBD_CODE());
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }

            });
        });

        initEdit(imagename, s -> {
            drawingpathData(s);

        });
    }
    private void saveImage(Bitmap bmp,String bd_code) {
        File appDir = new File(Environment.getExternalStorageDirectory().getPath() + "/BrePdaImage/");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = bd_code +".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void drawingpathData(String bd_code) {
        FreeUI_EntityCallBack<BaseResponseBean<DrawingpathEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<DrawingpathEntity>>
                (new TypeToken<BaseResponseBean<DrawingpathEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<DrawingpathEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(ImageMainActivity.this, true, getSupportFragmentManager())) {
                    DrawingpathEntity body = response.body().getResponse().getBody();
                    if (stringtoBitmap(body.getFILE_STREAM()) != null) {
                        saveImage(stringtoBitmap(body.getFILE_STREAM()),bd_code);
                        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/BrePdaImage/"+bd_code+".jpg");
                        Glide.with(ImageMainActivity.this).load(file).into(image);
                        for (String s:getAllDataFileName(Environment.getExternalStorageDirectory().getPath() + "/BrePdaImage/")){
                            if (!s.equals(bd_code+".jpg")){
                                File file1 = new File(Environment.getExternalStorageDirectory().getPath() + "/BrePdaImage/"+s);
                                file1.delete();
                            }
                        }
                    } else {
                        image.setImageDrawable(MyApp.app.getResources().getDrawable(R.drawable.ic_launcher_background));
                    }
                    image.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<DrawingpathEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "DRAWINGPATH");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("BD_CODE", bd_code);
        NetUtils.requestPostNet("IF.DRAWINGPATH", "GETDRAWINGPATH", ImageMainActivity.this, map, callBack);
    }

    public ArrayList<String> getAllDataFileName(String folderPath){
        ArrayList<String> fileList = new ArrayList<>();
        File file = new File(folderPath);
        File[] tempList = file.listFiles();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                String fileName = tempList[i].getName();
                if (fileName.endsWith(".jpg")){
                    fileList.add(fileName);
                }
            }
        }
        return fileList;
    }

    @Override
    protected void initData() {

        lotScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT1);
            }
        });
        imageScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT2);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            String qrResult = data.getStringExtra("SCAN_RESULT"); // 获取扫码结果
            if (qrResult != null) {
                switch (requestCode) {
                    case REQUEST_CODE_TEXT1:
                        etLot.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT2:
                        imagename.setText(qrResult);
                        break;
                }
            }

        }
    }


}
